package com.kgc.scd.controller;

import com.kgc.scd.bean.Order;
import com.kgc.scd.bean.OrderItem;
import com.kgc.scd.bean.Seckill;
import com.kgc.scd.contant.CommonConstant;
import com.kgc.scd.service.SeckillOrderService;
import com.kgc.scd.util.MyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Created On : 2022/6/7.
 * <p>
 * Author     : 98730
 * <p>
 * Description: 秒杀抢购业务入口
 */
@Slf4j
@RestController
public class SeckillBuyController {

    @Autowired(required = false)
    private SeckillOrderService seckillOrderService;

    @PostMapping("/seckillOrder")
    public Order seckillOrder(@RequestParam String userId, @RequestParam String seckillId){
        // 根据seckillid查询商品实体
        log.info("-------seckillId:{}",seckillId);
        Seckill seckill = seckillOrderService.queryProIdByseckillId(seckillId);
        String proId = seckill.getSeckillProid();

        // 创建订单实体
        Order order = new Order();
        order.setOrderUid(userId);
        // 生成抢购订单
        String seckillNo = "SC"
                + LocalDateTime.now().format(DateTimeFormatter.ofPattern(CommonConstant.TIME_PATTERN_MINUTE))
                + MyUtils.generateNonceStrUseUUID(4);
        // 将订单编号存入实体
        order.setOrderId(seckillNo);
        log.info("----------seckillNo:{}",seckillNo);
        // 设置抢购订单转台：0-未支付
        order.setOrderState(0);

        // 插入订单详情实体
        log.info("----------order:{}",order);
        OrderItem orderItem = OrderItem.builder()
                .itemNum(1)
                .itemOrderid(seckillNo)
                .itemProid(proId).itemComment(0).build();
        seckillOrderService.addSeckillOrderItem(orderItem);

        seckillOrderService.addSeckillOrder(order);


        log.info("----- 抢购订单实体：{} -----",order);

        return order;
    }

    @PostMapping("/SelectProIdBySeckillId")
    public Seckill SelectProIdBySeckillId(@RequestParam String seckillId){
        return seckillOrderService.queryProIdByseckillId(seckillId);
    }
}